package com.lhm.controller;

import com.lhm.entity.MyUser;
import com.lhm.service.UserService;
import com.lhm.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/adm/user")
public class UserController {
    @Autowired
    UserService userService;


    @RequestMapping("/findAll/{start}/{num}")
    public Map<String, Object> findall(@PathVariable("start") Integer start,@PathVariable("num")  Integer num) {
        Map<String, Object> map = new HashMap();
        map.put("total", 0);
        System.out.println("findAll=" + start  + num);
        if (start == null) {
            start = 0;
        }
        if (num == null) {
            num = 10;
        }

        map.put("total", userService.getCount());
        map.put("users",userService.findAll(start, num));
        return RespJson.pack(200, "", map);
    }

    //添加
    @RequestMapping("/addAdm")
    public Map<String, Object> addUser(String account, String password, String nickname, String phone) {

        MyUser u = new MyUser();
        u.setRole("G");
        u.setPassword(password);
        u.setAccount(account);
        u.setPhone(phone);
        u.setNickname(nickname);
        userService.add(u);
        return RespJson.pack(200, "添加管理员成功 ...", null);
    }
//根据id查找
    @RequestMapping("/findById/{id}")
    public Map<String, Object> findById(@PathVariable("id") int id) {
        MyUser u = userService.findById(id);
        return RespJson.pack(200, "", u);
    }
//密码重置成功
    @RequestMapping("/resetPwd/{uid}")
    public Map<String, Object> resetPwd(@PathVariable("uid") int uid) {
        Map<String, Object> map = new HashMap();
        map.put("id", uid);
        map.put("password", "111111");
        map.put("closed", 0);
        userService.update(map);
        return RespJson.pack(200, "密码重置成功", "");
    }

    //冻结成功
    @RequestMapping("/close/{uid}")
    public Map<String, Object> close(@PathVariable("uid") int uid) {
        Map<String, Object> map = new HashMap();
        map.put("id", uid);
        map.put("closed", 1);
        userService.update(map);
        return RespJson.pack(200, "冻结成功", "");
    }

    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
